/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of libgp2x.

    libgp2x is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    libgp2x is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libgp2x; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>

#include "gp2x_hardware.h"

pthread_t GP2x_kernel_thread;
void* GP2x_sdl_screen;

unsigned char GP2x_hardware_exit;

void GP2x_hardware_init() {
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }

    SDL_screen = SDL_SetVideoMode(320, 240, 16, SDL_SWSURFACE|SDL_DOUBLEBUF);
    if(SDL_screen == NULL) {
        fprintf(stderr, "Unable to set 320x240 video: %s\n", SDL_GetError());
        exit(1);
    }

    GP2x_sdl_screen = SDL_screen->pixels;

    GP2x_register(GP2x_REG_BUTTONS_1) = 0xFFFF;
    GP2x_register(GP2x_REG_BUTTONS_2) = 0xFFFF;
    GP2x_register(GP2x_REG_JOYSTICK) = 0xFFFF;

    GP2x_register(0x290E) = GP2x_register(0x2912) = 0x03101000 & 0xFFFF;
    GP2x_register(0x2910) = GP2x_register(0x2914) = 0x03101000 >> 16;

    GP2x_hardware_exit = 0;
    memset(&GP2x_kernel_thread, 0, sizeof(pthread_t));
    if(pthread_create(&GP2x_kernel_thread, NULL, GP2x_kernel, NULL) != 0) {
        fprintf(stderr, "Failed to create kernel thread.\n");
        exit(1);
    }
}

void GP2x_hardware_finalize() {
    GP2x_hardware_exit = 1;
    pthread_join(GP2x_kernel_thread, NULL);
    SDL_screen->pixels = GP2x_sdl_screen;
    SDL_Quit();
}

void* GP2x_kernel(void* args) {
    while(!GP2x_hardware_exit) {
        GP2x_hardware_events();
        GP2x_hardware_screen();

        SDL_Delay(10);
    }
    pthread_exit(NULL);
    return NULL;
}
